"use client";

import React, { useState, useEffect, useCallback } from 'react';
import { 
  Card, Table, Button, 
  Tag, Typography, Image, Space, message
} from "antd";
import type { TablePaginationConfig } from 'antd';
import { PlusOutlined, EyeOutlined, DownloadOutlined } from "@ant-design/icons";
import AdminLayout from "@/components/AdminLayout";
import { adminAPI, adminUserAPI } from "@/lib/api";
import type { Article, Category, AdminUser } from "@/lib/api";
import { useDataFetching } from "@/hooks/useDataFetching";
import { useCrudOperations } from "@/hooks/useCrudOperations";
import SearchFilters from "@/components/common/SearchFilters";
import TableActionColumn from "@/components/common/TableActionColumn";

const { Text } = Typography;

export default function ArticlesManagement() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
  const [selectedStatus, setSelectedStatus] = useState<boolean | null>(null);
  const [selectedUser, setSelectedUser] = useState<number | null>(null);
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [exportLoading, setExportLoading] = useState(false);

  // 使用通用数据获取Hook
  const {
    data: articles,
    loading,
    pagination,
    fetchData: fetchArticles
  } = useDataFetching<Article>({
    fetchFunction: adminAPI.getArticles,
    errorMessage: '获取文章列表失败'
  });

  // 使用通用CRUD操作Hook
  const {
    handleDelete: handleDeleteArticle,
    handleAdd: handleAddArticle,
    handleEdit: handleEditArticle,
    handlePreview: handlePreviewArticle
  } = useCrudOperations({
    deleteFunction: adminAPI.deleteArticle,
    onDeleteSuccess: () => {
      fetchArticles({
        page: pagination.current,
        limit: pagination.pageSize,
        keyword: searchKeyword || undefined,
        categoryId: selectedCategory || undefined,
        status: selectedStatus || undefined,
        userId: selectedUser || undefined,
      });
    },
    deleteSuccessMessage: '文章删除成功',
    deleteErrorMessage: '删除文章失败'
  });

  // 获取分类列表
  const fetchCategories = useCallback(async () => {
    try {
      const response = await adminAPI.getCategories();
      if (response.success) {
        setCategories(response.data);
      }
    } catch {
      console.error('获取分类列表失败');
    }
  }, []);

  // 获取用户列表
  const fetchUsers = useCallback(async () => {
    try {
      const response = await adminUserAPI.getUsers();
      if (response.success) {
        setUsers(response.data);
      }
    } catch {
      console.error('获取用户列表失败');
    }
  }, []);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    fetchArticles({
      page: 1,
      limit: pagination.pageSize,
      keyword: value || undefined,
      categoryId: selectedCategory || undefined,
      status: selectedStatus || undefined,
      userId: selectedUser || undefined,
    });
  };

  // 处理分类筛选
  const handleCategoryChange = (value: number | null) => {
    setSelectedCategory(value);
    fetchArticles({
      page: 1,
      limit: pagination.pageSize,
      keyword: searchKeyword || undefined,
      categoryId: value || undefined,
      status: selectedStatus || undefined,
      userId: selectedUser || undefined,
    });
  };

  // 处理状态筛选
  const handleStatusChange = (value: boolean | null) => {
    setSelectedStatus(value);
    fetchArticles({
      page: 1,
      limit: pagination.pageSize,
      keyword: searchKeyword || undefined,
      categoryId: selectedCategory || undefined,
      status: value || undefined,
      userId: selectedUser || undefined,
    });
  };

  // 处理用户筛选
  const handleUserChange = (value: number | null) => {
    setSelectedUser(value);
    fetchArticles({
      page: 1,
      limit: pagination.pageSize,
      keyword: searchKeyword || undefined,
      categoryId: selectedCategory || undefined,
      status: selectedStatus || undefined,
      userId: value || undefined,
    });
  };

  const handleTableChange = (newPagination: TablePaginationConfig) => {
    fetchArticles({
      page: newPagination.current!,
      limit: newPagination.pageSize!,
      keyword: searchKeyword || undefined,
      categoryId: selectedCategory || undefined,
      status: selectedStatus || undefined,
      userId: selectedUser || undefined,
    });
  };

  // 处理导出
  const handleExport = async () => {
    setExportLoading(true);
    try {
      const blob = await adminAPI.exportArticles({
        keyword: searchKeyword || undefined,
        categoryId: selectedCategory || undefined,
        status: selectedStatus || undefined,
        userId: selectedUser || undefined,
      });
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      
      // 生成文件名
      const now = new Date();
      const dateStr = now.toISOString().split('T')[0];
      link.download = `文章列表_${dateStr}.xlsx`;
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败');
    } finally {
      setExportLoading(false);
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchCategories();
    fetchUsers();
    fetchArticles({
      page: 1,
      limit: 10
    });
  }, [fetchCategories, fetchUsers, fetchArticles]);

  const columns = [
    {
      title: '封面图',
      dataIndex: 'coverImage',
      key: 'coverImage',
      width: 100,
      render: (url: string) => url ? <Image src={url} width={80} height={60} style={{ objectFit: 'cover' }} alt="文章封面" /> : '无',
    },
    {
      title: "文章标题",
      dataIndex: "title",
      key: "title",
      render: (text: string) => <Text strong>{text}</Text>,
      ellipsis: true,
    },
    {
      title: "文章摘要",
      dataIndex: "summary",
      key: "summary",
      width: 200,
      render: (text: string) => text ? <Text ellipsis={{ tooltip: text }}>{text}</Text> : '--',
      ellipsis: true,
    },
    {
      title: "作者",
      dataIndex: "author",
      key: "author",
      width: 120,
    },
    {
      title: "分类",
      dataIndex: "category",
      key: "category",
      width: 100,
      render: (category: Category) => <Tag color="blue">{category?.name}</Tag>,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 80,
      render: (status: boolean) => (
        <Tag color={status ? "green" : "red"}>
          {status ? "已发布" : "草稿"}
        </Tag>
      ),
    },
    {
      title: "置顶",
      dataIndex: "isTop",
      key: "isTop",
      width: 60,
      render: (isTop: boolean) => (
        <Tag color={isTop ? "orange" : "default"}>
          {isTop ? "置顶" : "-"}
        </Tag>
      ),
    },
    {
      title: "推荐",
      dataIndex: "isRecommend",
      key: "isRecommend",
      width: 60,
      render: (isRecommend: boolean) => (
        <Tag color={isRecommend ? "purple" : "default"}>
          {isRecommend ? "推荐" : "-"}
        </Tag>
      ),
    },
    {
      title: "阅读量",
      dataIndex: "views",
      key: "views",
      width: 80,
      render: (views: number) => (
        <span>
          <EyeOutlined style={{ marginRight: 4 }} />
          {views.toLocaleString()}
        </span>
      ),
    },
    {
      title: "发布时间",
      dataIndex: "publishedAt",
      key: "publishedAt",
      width: 150,
      render: (text: string) => text ? new Date(text).toLocaleDateString() : '--',
    },
    {
      title: "操作",
      key: "action",
      fixed: 'right' as const,
      width: 150,
      render: (_: unknown, record: Article) => (
        <TableActionColumn
          record={record}
          onEdit={(record) => handleEditArticle('/admin/articles/edit', record.id)}
          onDelete={handleDeleteArticle}
          onPreview={(record) => handlePreviewArticle('/discover/detail', record.slug)}
          editTooltip="编辑"
          deleteTooltip="删除"
          previewTooltip="预览"
          deleteConfirmTitle="确定要删除这篇文章吗？"
        />
      ),
    },
  ];

  return (
    <AdminLayout>
      <Card
        title="文章管理"
        extra={
          <Space>
            <Button
              icon={<DownloadOutlined />}
              onClick={handleExport}
              loading={exportLoading}
            >
              导出Excel
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => handleAddArticle('/admin/articles/edit')}
            >
              新建文章
            </Button>
          </Space>
        }
      >
        <div style={{ marginBottom: 16 }}>
          <SearchFilters
            searchKeyword={searchKeyword}
            selectedCategory={selectedCategory}
            selectedStatus={selectedStatus}
            selectedAuthor={selectedUser}
            categories={categories}
            users={users}
            onSearch={handleSearch}
            onCategoryChange={handleCategoryChange}
            onStatusChange={handleStatusChange}
            onAuthorChange={handleUserChange}
            searchPlaceholder="输入关键词搜索"
            categoryPlaceholder="选择分类"
            statusPlaceholder="选择状态"
            authorPlaceholder="选择创作者"
            showAuthorFilter={true}
          />
        </div>
        <Table
          columns={columns}
          dataSource={articles}
          rowKey="id"
          loading={loading}
          pagination={{ 
            ...pagination, 
            total: pagination.total,
            showTotal: (total, range) => `共 ${total} 条记录，第 ${range[0]}-${range[1]} 条`,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            showLessItems: true,
          }}
          onChange={handleTableChange}
          scroll={{ x: 1300 }}
        />
      </Card>
    </AdminLayout>
  );
} 